import axios, {AxiosProgressEvent, AxiosResponse, InternalAxiosRequestConfig} from 'axios'
import {getToken, removeToken} from "@/utils/auth";
import global from "@/dict/global";
import {ElLoading} from "element-plus";
import router from "@/router";
import {msgError} from "@/utils/alert";


let loading: any;
const startLoading = () => {
    loading = ElLoading.service({
        background:'rgba(0, 0, 0, 0.5)',
        lock:true,
        text:'请稍候……'
    })
}
const stopLoading = () => {
    loading.close()
}

axios.defaults.baseURL = import.meta.env.VITE_APP_BASE_API
axios.defaults.timeout = 5000

// request拦截器
axios.interceptors.request.use((config: InternalAxiosRequestConfig) => {

    // startLoading()

    // adminToken设置
    const adminToken = getToken(global.adminToken)
    if (adminToken) {
        config.headers[global.adminToken] = getToken(global.adminToken) // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config

}, error => {

    // startLoading()

    return Promise.reject(error)
})

// 响应拦截器
axios.interceptors.response.use((response: AxiosResponse) => {

    // stopLoading()

    // 二进制数据则直接返回
    if (response.request && (response.request.responseType === 'blob' || response.request.responseType === 'arraybuffer')) {
        return response
    }

    let error: number = response.data.error
    let errMsg: string = response.data.msg

    if (error != 0){
        msgError(errMsg)
        if (error == 10001){    // 登录超时，跳转到登录页
            console.log("error", error)
            removeToken(global.adminToken)
            router.push("/login")
        }
        return Promise.reject(errMsg)
    }
    return response

}, error => {

    // loading
    // stopLoading()

    console.log("error",error)

    let {message} = error;

    if (message == "Network Error") {
        message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
        message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
        message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    // 错误提示
    msgError(message)
    // 返回
    return Promise.reject(error)
})

export  const simpleGet = async (url:string, params:object = {}) => {
    let { data } = await axios.get(url, {params:params})
    return data
}

export const simplePost = async (url:string, data:object = {}) => {
    let res = await axios.post(url, data)
    return res.data
}


/**
 * 导出下载
 * @param url
 * @param where
 */
export const download = (url:string, where:any = {}) => {
    startLoading()
    where = where||{}
    let res = axios.post(url, where,{
        responseType: 'blob',
        onDownloadProgress: (progressEvent: AxiosProgressEvent) =>{
            // 文件总大小
            const size = progressEvent.event.currentTarget.response?.size
            //progressEvent.loaded 下载文件的当前大小
            //progressEvent.total  下载文件的总大小 如果后端没有返回 请让他加上！
            let progressBar = Math.round( progressEvent.loaded / size * 100);
            //接收进度为99%的时候需要留一点前端编译的时间
            if(progressBar >= 100){
                stopLoading()
                // this.percentage = 99;
                // this.$message.success("下载完成，文件正在编译。");
                // this.title = '下载完成，文件正在编译。';
            }else{
                // this.percentage = progressBar;
                // this.$message("正在下载，请稍等。");
                // this.title = '正在下载，请稍等。';
            }
            // console.log(progressEvent)
        },
    }).then((res) => {

        let disposition = res.headers['content-disposition']
        let filename = decodeURI(disposition.substring(disposition.lastIndexOf("filename*=UTF-8''")+17, disposition.length))
        let blob = new Blob([res.data])

        // @ts-ignore
        if (window.ActiveXObject || "ActiveXObject" in window){ // ie浏览器
            // @ts-ignore
            navigator.msSaveBlob(blob, filename)
        }else{
            const elink: any = document.createElement('a')
            elink.download = filename
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
            document.body.removeChild(elink)
        }

        // stopLoading()

    }).catch((err) => {
        stopLoading()
    })

}

export default axios
